<template>
	<view class="content" :style="{height:pageConfig.scrollHeight}">
		<u-toast ref="uToastMsg"></u-toast>
		<u-navbar>
			<view class="u-nav-slot navbar-select x-f" slot="left">

				<view class="navbar-select-t comboSelect">
					<uni-data-select placeholder="请添加设备" v-model="CheckHisValue" :localdata="HistoryDeviceList"
						iconColor="#fff" :clear="false" @change="ChangeAgreement"></uni-data-select>
				</view>

			</view>

			<view class="u-nav-slot" slot="right">
				<m-capsule :closeCurrent="closeAll ? 9999 : 1"></m-capsule>
			</view>
		</u-navbar>

		<view class="MainBox">
			<!-- 添加设备 -->
			<view class="TitleText" style="padding: 0 15px;">
				<text>添加设备</text>
			</view>
			<!-- 搜寻设备 -->
			<u-sticky offset-top="68">
				<view class="StickyBox">
					<view>
						<view class="StickyText" v-if="!BluetoothStatus">
							<view class="RoundRed"></view>
							<text class="Text">停止搜索...</text>
						</view>

						<view class="StickyText" v-if="BluetoothStatus && !deviceObj.deviceId">
							<view class="Round"></view>
							<text class="Text">自动搜寻设备中...</text>
						</view>

						<view class="StickyText" v-if="BluetoothStatus && deviceObj.deviceId">
							<view class="Round"></view>
							<text class="Text">设备已连接</text>
						</view>
					</view>
					<view class="StickyText">
						<uni-icons type="settings" size="12"></uni-icons>
						<view class="Text">
							设备协议:
							<view class="TextBox" v-if="selectedAgreement.DeviceName">
								{{ selectedAgreement.DeviceName }} -
								{{ selectedAgreement.MeasureName+selectedAgreement.MeasureSpec }}
							</view>

							<text class="NotText" v-else>未选择 设备协议</text>
						</view>
					</view>
					<view class="refreshBox" @click="refreshConnectScan">
						<uni-icons type="loop" size="14" color="#00aa00"></uni-icons>刷新设备

					</view>
				</view>
			</u-sticky>

			<view>
				<!-- <u-button text="anniu" @click="TurnBackFindBlue"></u-button> -->
			</view>


			<!-- 蓝牙链接操作盒子 -->
			<!-- -->
			<view style="padding: 0 15px;">

				<view class="BlueToothBox">
					<!-- 蓝牙连接 -->
					<view v-if="selectedAgreement.Communication == 'Bluetooth'">

						<view v-if="BluetoothStatus">

							<view v-if="BluetoothDeviceList.length">
								<u-list height="35vh">
									<u-list-item v-for="(item, index) in BluetoothDeviceList" :key="index">
										<u-cell>
											<view slot="title" style="display: flex;">
												<Volume :num="item.RSSI"></Volume>
												<view style="line-height: 35px;">{{item.name}}</view>
											</view>
											<view slot="value">
												<u-button v-if="deviceObj.deviceId != item.deviceId" text="连接"
													size="small" type="success" @click="connectDevice(item)"></u-button>

												<u-button v-else text="断开" size="small" type="error"
													@click="DisconnectBtn(item.deviceId)"></u-button>

											</view>
										</u-cell>
									</u-list-item>
								</u-list>
							</view>

							<u-empty v-else :text="selectedAgreement.DeviceName ? '请将手机尽量靠近要添加的设备' : '请先选择设备'"
								iconSize="150" icon="/static/tabbar-icons/openBluetooth.png"></u-empty>

						</view>

						<u-empty v-else text="开启蓝牙,以便查找附近蓝牙设备" iconSize="150" icon="/static/tabbar-icons/Bluetooth.png"
							style="height:'35vh'">
							<u-button @click="openBluetoothAdapter" size="small" type="primary"
								:style="{marginTop:10+'px'} " text="立即开启"></u-button>
						</u-empty>

					</view>


					<!-- 串口 -->
					<view v-else-if="selectedAgreement.Communication == 'Serial'" style="padding: 10px 15px;">
						<!-- Serial -->
						<view v-if="SignalR_Status">
							<view v-if="BluetoothDeviceList.length">
								<view v-if="!showSerial">
									<u-list height="35vh">
										<u-list-item v-for="(item, index) in BluetoothDeviceList" :key="index">
											<u-cell>
												<view slot="title" style="display: flex;">
													<!-- <Volume :num="item.RSSI"></Volume> -->
													<view style="line-height: 35px;">{{item.clientName}}</view>
												</view>
												<view slot="value">
													<u-button v-if="deviceObj.deviceId != item.deviceId" text="参数配置"
														size="small" type="success"
														@click="connectSerial(item)"></u-button>

													<u-button v-else text="断开" size="small" type="error"
														@click="DisconnectBtn(item.deviceId)"></u-button>

												</view>
											</u-cell>
										</u-list-item>
									</u-list>
								</view>
								<view v-if="showSerial">
									<uni-forms ref="SerialForm" :modelValue="SerialFormData" label-position="left"
										class="FormDataBox">
										<uni-forms-item name="SerialDeviceName">
											<uni-data-select v-model="SerialFormData.SerialDeviceName"
												:localdata="SerialDeviceNameList" label="设备名" placeholder="请选择设备名"
												disabled></uni-data-select>
										</uni-forms-item>
										<uni-forms-item name="portName">
											<uni-data-select v-model="SerialFormData.portName" :localdata="portNameList"
												label="串口号" placeholder="请选择串口号" @change="selectChange($event,1)"
												:clear="false"></uni-data-select>
										</uni-forms-item>
										<uni-forms-item name="BaudRate">
											<uni-data-select v-model="SerialFormData.BaudRate" :localdata="BaudRateList"
												label="波特率" placeholder="请选择波特率" @change="selectChange($event,2)"
												:clear="false"></uni-data-select>
										</uni-forms-item>
										<uni-forms-item name="DataBits">
											<uni-data-select v-model="SerialFormData.DataBits" :localdata="DataBitsList"
												label="数据位" placeholder="请选择数据位" @change="selectChange($event,3)"
												:clear="false"></uni-data-select>
										</uni-forms-item>
										<uni-forms-item name="StopBits">
											<uni-data-select v-model="SerialFormData.StopBits" :localdata="StopBitsList"
												label="停止位" placeholder="请选择停止位" @change="selectChange($event,4)"
												:clear="false"></uni-data-select>
										</uni-forms-item>
										<uni-forms-item name="ParityBit">
											<uni-data-select v-model="SerialFormData.ParityBit"
												:localdata="ParityBitList" label="校验位" placeholder="请选择校验位"
												@change="selectChange($event,5)" :clear="false"></uni-data-select>
										</uni-forms-item>
										<!-- <uni-forms-item name="BaudRate">
																		<uni-data-select v-model="SerialFormData.BaudRate" :localdata="BaudRateList" label="流控制"
																			placeholder="请选择流控制"></uni-data-select>
																	</uni-forms-item> -->
										<view style="display: flex;flex-direction: row;">
											<u-button text="返回列表" size="small" type="success"
												style="flex: 1;margin:10rpx" @click="showSerial=false"></u-button>
											<u-button text="重置" size="small" type="success" style="flex: 1;margin:10rpx"
												@click="resetSerialFormData"></u-button>
											<u-button text="连接" size="small" type="success" style="flex: 1;margin:10rpx"
												@click="connectDevice(curdeviceObj)"></u-button>
										</view>

									</uni-forms>
								</view>
							</view>
							<u-empty v-else text="没有可以连接的串口设备,请尝试刷新" iconSize="150"
								icon="/static/tabbar-icons/openBluetooth.png"></u-empty>
						</view>
						<u-empty v-else
							text="请连接SignalR                                                                       "
							iconSize="150" icon="/static/tabbar-icons/openBluetooth.png">
							<u-button @click="toSignalrTab" size="small" type="primary" :style="{marginTop:10+'px'} "
								text="连接SignalR"></u-button>
						</u-empty>
					</view>

					<!-- HID模式，蓝牙配对 -->
					<view v-else-if="selectedAgreement.Communication == 'HID'">
						<u-empty mode="history" icon="/static/Image/Img/history.png" iconSize="120" text="请手动配对设备">
						</u-empty>
					</view>

					<!-- 未选过设备 -->
					<view v-else>
						<u-empty mode="history" icon="/static/Image/Img/history.png" iconSize="120" text="请先选择需要连接的设备">
						</u-empty>

					</view>

				</view>


			</view>



			<!-- 标题 -->
			<view class="TitleBox" style="padding: 0 15rpx;">
				<text class="LeftTitle">选择设备类型</text>
			</view>

			<Device :DeviceList="DeviceList"></Device>

		</view>

		<!-- 导航栏右侧按钮 -- 遮罩层 -->
		<u-overlay :show="ShowRightNav" v-if="ShowRightNav" @click="ShowRightNav = false" opacity="0.4">
			<view class="warp">
				<view class="rect" @tap.stop style="overflow: hidden;">
					<u-cell title="添加设备">
						<u-icon slot="icon" size="16" name="plus"></u-icon>
					</u-cell>
					<u-cell title="扫一扫">
						<u-icon slot="icon" size="20" name="scan"></u-icon>
					</u-cell>
				</view>
			</view>
		</u-overlay>


	</view>
</template>

<script>
	import Device from "./Device/Device.vue";
	import Volume from "./Device/signal.vue";
	import AgreementJs from "@/static/js/Agreement.js";
	var Agreement = AgreementJs;

	export default {
		props: {
			config: {
				type: Object,
				default: () => {
					return {
						tabbarHeight: 0,
						scrollHeight: 500
					}
				}
			},
			isPage: {
				type: Boolean,
				default: () => {
					return true
				}
			},
		},
		components: {
			Device,
			Volume
		},
		data() {
			return {
				closeAll: true, // 是否返回首页
				donotSetFalseByOnUnload: false, // 卸载页面时是否设置false
				SignalR_Status: false,
				SignalRConnect: null,
				BluetoothType: true,
				// SelectValue: 0,
				// HistoryDeviceList: [], // 历史设备
				range: [],
				ShowRightNav: false,
				BluetoothStatus: false, // 记录是否有设别连接
				// 设备列表
				DeviceList: [],
				msg: '还未开始',
				log: '',
				BluetoothDeviceList: [], // 搜索到的蓝牙列表
				deviceMap: {},
				toBottom: '',
				// deviceObj: {
				// 	deviceId: '',
				// },
				// selectedAgreement: {},
				//当前协议对象
				// agreement: {},
				SerialFormData: {
					SerialDeviceName: 0,
					portName: "",
					BaudRate: "",
					DataBits: "",
					StopBits: "",
					ParityBit: "",
				},
				SerialDeviceNameList: [],
				portNameList: [],
				BaudRateList: [{
						value: 0,
						text: "100"
					},
					{
						value: 1,
						text: "300"
					},
					{
						value: 2,
						text: "600"
					},
					{
						value: 3,
						text: "1200"
					},
					{
						value: 4,
						text: "2400"
					},
					{
						value: 5,
						text: "4800"
					},
					{
						value: 6,
						text: "9600"
					},
					{
						value: 7,
						text: "14400"
					},
					{
						value: 8,
						text: "19200"
					},
					{
						value: 9,
						text: "38400"
					},
					{
						value: 10,
						text: "56000"
					},
					{
						value: 11,
						text: "57600"
					},
					{
						value: 12,
						text: "115200"
					},
				], // 波特率下拉数据
				DataBitsList: [{
						value: 0,
						text: "5"
					},
					{
						value: 1,
						text: "6"
					},
					{
						value: 2,
						text: "7"
					},
					{
						value: 3,
						text: "8"
					},
				], //数据位下拉数据
				StopBitsList: [{
						value: 0,
						text: "1"
					},
					{
						value: 1,
						text: "1.5"
					},
					{
						value: 2,
						text: "2"
					},
				], //停止位下拉数据
				ParityBitList: [{
						value: 0,
						text: "0"
					},
					{
						value: 1,
						text: "1"
					},
					{
						value: 2,
						text: "2"
					},
					{
						value: 3,
						text: "3"
					},
					{
						value: 4,
						text: "4"
					},
				], //校验位下拉数据
				showSerial: false, //显示隐藏串口参数
				curdeviceObj: {}, //选择的串口设备
				pageIsOpen: false,
			}
		},
		computed: {
			pageConfig() {
				console.log(this.config);
				let config = this.$utils.deepClone(this.config);
				if (this.isPage) {
					uni.createSelectorQuery().select('.content').boundingClientRect(data => {
						scrollHeight = data.height;
						console.log(scrollHeight);

						config["scrollHeight"] = scrollHeight + 'px';
						openPage();
					}).exec();
				} else {
					config["scrollHeight"] += 'px';
				}

				return config;
			},
			agreement() {
				let agreementInfo = this.$store.getters["QmsModule/DeviceAgreement"] || {};
				console.log(agreementInfo);
				return agreementInfo;
			},
			HistoryDeviceList() { // 获取历史设备
				return this.$store.getters['QmsModule/DeviceHistory'];
			},
			CheckHisValue: { // 获取记录的选中索引
				get() {
					// 获取记录的选中索引
					return this.$store.state.QmsModule.DeviceLinkConfig.CheckHisValue || 0;
				},
				set(value) {
					console.log(value);
					this.$store.commit('QmsModule/ChangeAndSetStateData', {
						Name1: 'DeviceLinkConfig.CheckHisValue',
						data: value,
						StorageName: 'CheckHisValue',
						StorageData: value
					});
				}
			},
			selectedAgreement() { // 选中的协议信息
				if (!this.HistoryDeviceList.length ||
					this.CheckHisValue >= this.HistoryDeviceList.length) {
					return {};
				}
				return this.HistoryDeviceList[this.CheckHisValue];
			},
			DeviceLink_Content() {
				return this.$store.getters['QmsModule/DeviceLink_Content'];
			},
			deviceObj() {

				return this.$store.state.QmsModule.DeviceLinkConfig.Boolean.deviceObj;
			}
		},
		watch: {
			"selectedAgreement.Communication": { // 监听选中的协议类型
				handler(newVal, oldVal) {
					var that = this;
					// 清空列表数据,避免产生闪一下的动作
					that.BluetoothDeviceList = []
					// 如果前一个连接的协议类型是蓝牙的,那么直接停止扫描设备 
					if (oldVal == 'Bluetooth') {
						// 还要做一步,如果设备是连接状态,断开设备连接


						// 如果选中的设备协议类型依旧是蓝牙,
						if (newVal == 'Bluetooth') {
							// setTimeout(() => {
							that.refreshConnectScan();
							// }, 500);
						} else {
							console.log(that.agreement);
							that.agreement.StopFind();
						}
					} else {
						// 上一选中协议非蓝牙设备
						if (oldVal == 'Serial') { // 如果上一个选择的是串口

						} else if (oldVal == 'HID') {

						}
						// 新选中的是蓝牙协议
						if (newVal == 'Bluetooth') {
							that.refreshConnectScan();
						}
						// 新选中的是串口协议
						if (newVal == 'Serial') {
							that.refreshConnectScan();
						}
					}

				},
				deep: true
			},
		},
		onHide() { // 脱离当前页面时
			var that = this;
			// 离开页面的时候，将之后进入页面扫描的开启条件关闭
			that.$store.commit('QmsModule/ChangeAndSetStateData', {
				Name1: 'RecordScan',
				data: false
			})
			if (that.agreement && that.agreement.StopFind) {
				that.agreement.StopFind();
			}
		},
		onShow() { // 显示当前页面时
			var that = this;
			if (this.isPage) {
				if (that.$store.getters['QmsModule/DeviceHistory'].length) { // 如果有缓存的设备数据，赋值
					// 当选中项是蓝牙连接的设备时，开启搜索蓝牙
					if (that.selectedAgreement.Communication == 'Bluetooth') {
						// 只有在当前页已经存在，且无设备连接状态下，允许将协议重置
						if (this.pageIsOpen && !this.$store.state.QmsModule.DeviceLinkConfig.DeviceLink_Content) {
							setTimeout(() => {
								console.log(that.agreement);
								that.refreshConnectScan();
							}, 300);


						} else {
							setTimeout(() => {
								that.refreshConnectScan();
							}, 300);

						}
					}

				} else { // 如果没有历史设备的缓存，该清除的清除
					// 清除 选中的协议信息
					// that.selectedAgreement = {};
					// 清除 历史设备
					// that.HistoryDeviceList = [];
					// 将选中项 初始化
					// that.SelectValue = 0;
					that.CheckHisValue = 0;

					// 这个写法是在 vuex 中定义的修改state中的数据的
					// 需要重置的直接重置掉，可能没太大必要，因为在设置清除缓存会全部清掉，其他情况也不会去清
					that.$store.commit('QmsModule/ChangeAndSetStateData', {
						Name1: 'DeviceLinkConfig.DeviceHistory',
						data: []
					})

					that.$store.commit('QmsModule/ChangeAndSetStateData', {
						Name1: 'DeviceLinkConfig.CheckHisValue',
						data: 0
					});

					// 清除历史设备的缓存
					uni.removeStorageSync('Agreement_History_DevicesList');
					// 清除选中项的缓存
					uni.removeStorageSync('CheckHisValue');
				}

			}
		},
		onLoad(option) {
			// console.log(option);
			if (!this.$utils.isEmpty(option)) {
				this.closeAll = option.hideIcon == "true";
			}

			// 判断qms首页是否开启过智控
			let inControlPage = this.$store.state.QmsModule.DeviceLinkConfig.inControlPage;
			if (inControlPage) {
				// 如果首页开启过智控，那么新打开的智控页卸载时，就不要将inControlPage设置false了
				this.donotSetFalseByOnUnload = false;
			} else {
				this.donotSetFalseByOnUnload = true;
				// this.$store.commit('QmsModule/ChangeAndSetStateData', {
				// 	Name1: 'DeviceLinkConfig.inControlPage',
				// 	data: true
				// });
			}
			console.log(this.$store.state.QmsModule.DeviceLinkConfig.inControlPage);
		},
		created() {
			let that = this;


			// init，打开界面及调用获取蓝牙状态
			this.GetDeviceList();
			this.SignalRInit();
			// setTimeout(() => {
			// 	this.getBluetoothType();

			// }, 300)
			setInterval(() => {
				that.SignalR_Status = that.$store.getters['QmsModule/SignalR_Status'];
				//如果监听到SignalR断开连接，断开连接的终端，清空终端列表
				if (!that.SignalR_Status) {
					if (that.selectedAgreement.Communication == 'Serial') {
						that.agreement.Disconnect(that.curdeviceObj.deviceId);
						that.BluetoothDeviceList = [];
					}
				}
			}, 500);

		},
		mounted() {
			var that = this;

			this.$nextTick(() => {
				setTimeout(() => {
					that.getBluetoothType();
					that.pageIsOpen = true;
				}, 500);
			});


			//监听选中的设备协议回调
			uni.$once('callBackDeviceType', function(data) {
				// 当前选中的协议是蓝牙协议时，开启扫描
				if (data.Communication == 'Bluetooth') {
					that.refreshConnectScan();
				}
			});

			// 监听蓝牙适配器状态变化事件
			uni.onBluetoothAdapterStateChange(function(res) {
				console.log(res);

				if (that.BluetoothType != res.available) {
					that.BluetoothType = res.available
					if (res.available == true) { // 蓝牙适配器是否可用
						that.BluetoothStatus = true;
						that.refreshConnectScan();
						console.log(res.available)

					} else {

					}
				}

			})
		},
		beforeDestroy() {

			if (this.agreement && this.agreement.StopFind) {
				this.agreement.StopFind();
			}
		},
		onUnload() {
			if (this.donotSetFalseByOnUnload) {
				// 设置智控页已全部卸载，页面栈无智控页面
				this.$store.commit('QmsModule/ChangeAndSetStateData', {
					Name1: 'DeviceLinkConfig.inControlPage',
					data: false
				});
			}
		},
		methods: {
			onMyShow() {
				let that = this;
				if (that.$store.getters['QmsModule/DeviceHistory'].length) { // 如果有缓存的设备数据，赋值
					// 当选中项是蓝牙连接的设备时，开启搜索蓝牙
					if (that.selectedAgreement.Communication == 'Bluetooth') {
						// 只有在当前页已经存在，且无设备连接状态下，允许将协议重置
						console.log(this.$store.state.QmsModule.DeviceLinkConfig.DeviceLink_Content);
						if (this.pageIsOpen && !this.$store.state.QmsModule.DeviceLinkConfig.DeviceLink_Content) {
							setTimeout(() => {
								console.log(that.agreement);
								that.refreshConnectScan();
							}, 300);


						} else {
							setTimeout(() => {
								that.refreshConnectScan();
							}, 300);

						}
					}

				} else { // 如果没有历史设备的缓存，该清除的清除
					// 清除 选中的协议信息
					// that.selectedAgreement = {};
					// 清除 历史设备
					// that.HistoryDeviceList = [];
					// 将选中项 初始化
					// that.SelectValue = 0;
					that.CheckHisValue = 0;

					// 这个写法是在 vuex 中定义的修改state中的数据的
					// 需要重置的直接重置掉，可能没太大必要，因为在设置清除缓存会全部清掉，其他情况也不会去清
					that.$store.commit('QmsModule/ChangeAndSetStateData', {
						Name1: 'DeviceLinkConfig.DeviceHistory',
						data: []
					})

					that.$store.commit('QmsModule/ChangeAndSetStateData', {
						Name1: 'DeviceLinkConfig.CheckHisValue',
						data: 0
					});

					// 清除历史设备的缓存
					uni.removeStorageSync('Agreement_History_DevicesList');
					// 清除选中项的缓存
					uni.removeStorageSync('CheckHisValue');
				}
			},
			getBluetoothLink() { // 获取已连接的设备
				let that = this;
				console.log(123)
				console.log(that.BluetoothDeviceList)
				console.log(that.deviceObj)
				try {
					that.agreement.getConnected((data) => { // 获取已连接设备的返回值
						console.log(data)
						console.log(JSON.parse(data.devices))
						if (data.status == 2500) {
							let devices = JSON.parse(data.devices) || [];
							if (devices.length) {
								// 判断是否存在原有的数据中
								let hasDevice = that.BluetoothDeviceList.some(item => {
									return item.deviceId == devices[0].deviceId;
								})
								if (!hasDevice) {
									// 将已连接的设备插入
									that.BluetoothDeviceList.push(devices[0])
									// that.deviceObj = that.$utils.deepClone(devices[0]);

									that.$store.commit('QmsModule/ChangeAndSetStateData', {
										Name1: 'DeviceLinkConfig.Boolean.deviceObj',
										data: that.$utils.deepClone(devices[0])
									});
								}
							}
						}
					})

				} catch (err) {
					console.log(err)

				}
			},
			toSignalrTab() { //SignalR未连接跳转到SignalR连接
				// uni.switchTab({
				// 	url: '/pages/me/SettingPage'
				// });	
				uni.navigateTo({
					url: '/pages/me/SettingPage?openSignalR=1'
				});
				// uni.navigateTo({
				// 	url: '/pages/me/SettingPage'
				// });	
			},
			resetSerialFormData() { //重置串口参数
				var that = this;
				//that.SerialFormData.portName = "";
				that.SerialFormData.BaudRate = "";
				that.SerialFormData.DataBits = "";
				that.SerialFormData.StopBits = "";
				that.SerialFormData.ParityBit = "";
			},
			//显示串口参数页面，并获取PortName
			connectSerial(deviceObj) {
				var that = this;
				that.showSerial = true;
				var agreement = that.agreement;
				console.log(JSON.stringify(deviceObj));
				that.SerialDeviceNameList = [];
				that.SerialDeviceNameList.push({
					value: 0,
					text: deviceObj.clientName
				})
				that.curdeviceObj = deviceObj;
				agreement.getPortName(deviceObj.deviceId, (PortNameList) => {
					console.log(JSON.stringify(PortNameList))
					that.portNameList = PortNameList;
				});
			},
			//串口参数下拉框change事件
			selectChange(e, index) {
				var that = this;
				switch (index) {
					case 1: {
						that.$store.state.QmsModule.portName = that.portNameList[e].text;
						break;
					}
					case 2: {
						that.$store.state.QmsModule.BaudRate = that.BaudRateList[e].text;
						break;
					}
					case 3: {
						//console.log(JSON.stringify(that.DataBitsList[e].text));
						//console.log(JSON.stringify(that.SerialFormData.DataBits))
						that.$store.state.QmsModule.DataBits = that.DataBitsList[e].text;
						break;
					}
					case 4: {
						that.$store.state.QmsModule.StopBits = that.StopBitsList[e].text;
						break;
					}
					case 5: {
						that.$store.state.QmsModule.ParityBit = that.ParityBitList[e].text;
						break;
					}
					default: {

					}

				}
				//console.log(e);
				//console.log(index);
			},
			SignalRInit() {
				var that = this;
				//获取对象
				// that.SignalRConnect = that.$store.getters.SignalR_Connect;

				// that.SignalRConnect.invoke("GetTerminal", '006').catch(function(err) {});
				// //定义所有回调
				// //获取所有终端列表
				// that.SignalRConnect.on('onGetTerminal', function(terminalList) {
				// 	console.log(JSON.stringify(terminalList));
				// })



			},
			ChangeAgreement(index) { // 切换下拉框时，对协议信息赋值
				let that = this
				// 给 vuex 赋值

				// this.CheckHisValue = index;
				// console.log(index);
				// 在历史设备中的索引
				// that.$store.commit('QmsModule/ChangeAndSetStateData', {
				// 	Name1: 'DeviceLinkConfig.CheckHisValue',
				// 	data: index,
				// 	StorageName: "CheckHisValue",
				// 	StorageData: index
				// });
				// console.log(index);

				// 给页面上的选中协议赋值
				// that.selectedAgreement = that.HistoryDeviceList[index];
				// 获取选中的协议类型
				// that.DeviceType = that.HistoryDeviceList[index].Communication
			},
			startScan(agreemnetName) { // 开始扫描
				var that = this;
				var agreement1 = that.agreement;
				console.log(agreemnetName);
				agreement1.Link("", (devices) => {
					// console.log(that.BluetoothDeviceList)
					//加入搜索到的设备列表,因为蓝牙搜索到的数据是一条条返回的,且可能是重复的
					let list = [...that.BluetoothDeviceList];
					for (let i = 0; i < devices.length; i++) {
						let dev = devices[i];
						//去重
						if (that.deviceMap[dev.deviceId] >= 0) {
							let index = that.deviceMap[dev.deviceId];
							//更新
							list.splice(index, 1, dev);
						} else {
							//新增
							list.push(dev);
							that.deviceMap[dev.deviceId] = list.length - 1;
						}
					}

					that.BluetoothDeviceList = list;
				});
			},
			//重连设备连接
			refreshConnectScan() {
				var that = this;
				if (that.selectedAgreement.Communication == 'Bluetooth') {

					that.BluetoothDeviceList = [];
					that.deviceMap = {};
					//断开连接，重新连接
					console.log(that.agreement);
					try {
						if (!that.$utils.isEmpty(that.agreement)) {
							that.agreement.StopFind();
						}
					} catch (e) {}
					//判定是否选择过,已选择过的
					console.log(that.selectedAgreement.DeviceName);
					if (!that.$utils.isEmpty(that.selectedAgreement.DeviceName)) {
						// that.agreement = Agreement.createDeviceAgreement(that.selectedAgreement.BluetoothProtocol);
						that.startScan(that.selectedAgreement.BluetoothProtocol);
						that.getBluetoothLink(); // 获取已连接的设备
					}
				}

			},
			getBluetoothType() { // 获取手机蓝牙是否开启
				let that = this;

				let basicNum = 0;
				let sysDeviceInfo = JSON.parse(uni.getStorageSync('sysDeviceInfo'));
				if (sysDeviceInfo['osName'] == 'ios') {
					function getBluetoothInfo() {
						plus.bluetooth.getBluetoothAdapterState({
							success(ret) {
								if (basicNum < 4) {
									if (ret.code == 0) {
										basicNum++;
										getBluetoothInfo();
									}
								}

								if (ret.available) {
									basicNum = 0
									that.BluetoothStatus = true;
								}
							},
							fail(err) {
								console.log(JSON.stringify(err))
							}
						});
					}
					setTimeout(() => {
						getBluetoothInfo();
					}, 1000)
				} else {
					// Native.js for Android封装一条通过JS语法直接调用Native Java接口通道，通过plus.android可调用几乎所有的系统API
					const BluetoothAdapter = plus.android.importClass(
						'android.bluetooth.BluetoothAdapter'); // 引入Java 蓝牙类
					const blueadapter = BluetoothAdapter.getDefaultAdapter(); //拿到默认蓝牙适配器方法
					if (blueadapter) {
						setTimeout(() => {
							// 判断蓝牙是否开启
							if (blueadapter.isEnabled()) {
								// 已开启
								that.BluetoothStatus = true;
								//开启蓝牙后开始搜索蓝牙设备
								console.log('开启')

								that.refreshConnectScan();

							} else {
								console.log('关闭')
								// StopFind
								that.BluetoothStatus = false
								// this.ToOtherCloseFindBlue()
							}
						}, 50)
					}

				}

			},
			openBluetoothAdapter() {
				// bluetoothAdapter.enable();
				this.getBluetoothType()
				// uni.openBluetoothAdapter({
				// 	success(res) {
				// 		console.log('蓝牙适配器已打开')
				// 	},
				// 	fail(err) {
				// 		console.log('打开蓝牙适配器失败', err)
				// 	}
				// })
			},
			GetDeviceList() { // 获取分类
				var that = this

				that.Request.request('APP_JLSBFLLIST1', {}, function(res) {
					console.log(res);
					if (res.status == 200) {

						function tranList(list, rootVal, PID, ID) {
							var childItem = [];
							for (var i = 0; i < list.length; i++) {
								var childObj = {}
								if (list[i][PID] == rootVal) {
									childObj = list[i];
									childObj.children = tranList(list, list[i][ID], PID, ID);
									childItem.push(childObj);
								}
							}
							return childItem;
						}

						let TreeData = tranList(res.data.ds, 0, 'UpID', 'MeasureTypeID')

						TreeData[0].children.forEach(item => {
							let ChildrenList = []
							res.data.ds1.forEach(ReItem => {
								if (ReItem.UpID == item.MeasureTypeID) {
									ChildrenList.push(ReItem)
								}
							})
							item.children = ChildrenList
						})
						console.log(TreeData[0]);
						// console.log(JSON.stringify(TreeData))
						that.DeviceList = TreeData[0].children
					}
				})

			},
			tranList(list, rootVal, PID, ID) { // 将分类数据变成树型
				var childItem = [];
				for (var i = 0; i < list.length; i++) {
					var childObj = {}
					if (list[i][PID] == rootVal) {
						childObj = list[i];
						childObj.children = tranList(list, list[i][ID], PID, ID);
						childItem.push(childObj);
					}
				}
				return childItem;
			},
			connectDevice(deviceObj) { // 点击连接
				console.log(JSON.stringify(deviceObj))
				var that = this
				var agreement1 = that.agreement;

				agreement1.Link(deviceObj.deviceId, [], (devices) => {
					if (devices && devices.status == 2500) {
						// 连接成功
						// that.deviceObj.deviceId = deviceObj.deviceId
						// that.$store.state.QmsModule.deviceId = deviceObj.deviceId
						
						
						that.$store.commit('QmsModule/ChangeAndSetStateData', {
							Name1: 'DeviceLinkConfig.Boolean.deviceObj',
							data: that.$utils.deepClone(deviceObj)
						});

						// console.log(devices)

						// 去调用返回值的回调
						agreement1.CallBackGetData((data) => {
							console.log(data);
							uni.$emit("BluetoothData", data);
						})
						//协议的状态变更回调



						agreement1.GetStatus((deviceId, connected) => {
							// 设置设备连接状态
							that.$store.commit("QmsModule/ChangeAndSetStateData", {
								Name1: 'DeviceLinkConfig.DeviceLink_Content',
								data: connected
							});

							let ret = {
								deviceId: deviceId, // 设备ID
								connected: connected, // 设备连接状态
							};

							console.log(connected);

							that.$store.commit("QmsModule/ChangeAndSetStateData", {
								Name1: 'DeviceLinkConfig.Boolean.deviceTypeInfo',
								data: ret
							});

							if (that.deviceObj.deviceId == deviceId) {
								//监听到主动断开连接的，则自动断开，并从列表中减去
								console.log(!connected);
								if (!connected) {
									that.DisconnectBtn(that.deviceObj.deviceId, 1);
								}
							}
						});


						// that.$store.dispatch('QmsModule/GetDeviceStatus', {
						// 	agreement: agreement1,
						// 	callback: (res) => {
						// console.log(that.deviceObj.deviceId);
						// console.log(res);
						// uni.$m.utils.layer.alert('11')
						// let {
						// 	deviceId,
						// 	connected
						// } = res;
						// if (that.deviceObj.deviceId == deviceId) {
						// 	//监听到主动断开连接的，则自动断开，并从列表中减去
						// 	console.log(!connected);
						// 	if (!connected) {
						// 		that.DisconnectBtn(that.deviceObj.deviceId, 1);
						// 	}
						// }
						// }
						// })
						// agreement1.GetStatus((deviceId, connected) => {
						// 	console.log(connected);
						// 	if (that.deviceObj.deviceId == deviceId) {
						// 		//监听到主动断开连接的，则自动断开，并从列表中减去
						// 		if (!connected) {
						// 			that.DisconnectBtn(that.deviceObj.deviceId, 1);
						// 			that.BluetoothDeviceList = that.BluetoothDeviceList.filter((item) => {
						// 				return item.deviceId != deviceId
						// 			});
						// 			delete that.deviceMap[that.deviceObj.deviceId];
						// 			// console.log(1111)
						// 			uni.$emit("changeDeivceStatus", false);
						// 		}
						// 	}
						// });

						uni.showToast({
							title: '设备已连接',
							duration: 2000
						});

						that.$store.commit('QmsModule/ChangeAndSetStateData', {
							Name1: 'DeviceLinkConfig.DeviceLink_Content',
							data: true
						});
						//串口
						if (that.selectedAgreement.Communication == 'Serial') {
							that.showSerial = false;
						}
						//
					}
				});
			},
			DisconnectBtn(deviceId, IsTrue) { // 断开连接
				var that = this
				// console.log(JSON.stringify(deviceObj))
				var agreement1 = that.agreement;

				// that.BluetoothDeviceList = [];
				// that.deviceMap = {};

				agreement1.Disconnect(deviceId);

				that.$store.commit('QmsModule/ChangeAndSetStateData', {
					Name1: 'DeviceLinkConfig.DeviceLink_Content',
					data: false
				});
				// 断开设备后，修改设备状态
				uni.$m.utils.msg("设备已断开");


				uni.$emit("changeDeivceStatus", false);


				// that.deviceObj.deviceId = null;
				
				let deviceObj = that.$utils.deepClone(that.deviceObj)
				deviceObj['deviceId'] = null;
				
				that.$store.commit('QmsModule/ChangeAndSetStateData', {
					Name1: 'DeviceLinkConfig.Boolean.deviceObj',
					data: deviceObj
				});

				setTimeout(() => {

					that.refreshConnectScan();
				}, 300);
			},
			TurnBackFindBlue() { // 重新开始搜索设备
				var that = this
				that.BluetoothDeviceList = []
				if (that.selectedAgreement.BluetoothProtocol) {
					that.startScan(that.selectedAgreement.BluetoothProtocol)
				}
			},
			ToOtherCloseFindBlue() { // 传给组件的事件，让跳转页面时，关闭蓝牙搜索
				var that = this
				if (that.selectedAgreement.BluetoothProtocol) {
					// var agreement = that.agreement;
					// agreement.StopFind() // 停止扫描
				}
				// that.DisconnectBtn(that.$store.state.deviceId, 1)
			},
		}
	}
</script>

<style lang="scss">
	* {
		padding: 0;
		margin: 0;
		box-sizing: border-box;
	}

	.content {
		/* 给顶部盒子安全高度 */
		padding-top: var(--status-bar-height);
		background-color: #fff;


		// 顶部导航栏 navbar点击左侧会有改变透明的的操作，直接强制赋值为1
		.u-navbar__content__left {
			opacity: 1 !important;
		}

		.comboSelect {

			::v-deep .uni-stat-box {
				background-color: transparent !important;
			}

		}

		::v-deep .uni-select {
			min-width: 150px;
			border: none !important;

			.uni-select__input-box {

				.uni-select__input-text,
				.uni-select__input-placeholder {
					color: #fff !important;
				}

				// 下拉框内文字样式
				.uni-select__input-text {
					color: #fff !important;
				}

				.uni-icons {
					color: #fff !important;
				}
			}
		}
	}

	.u-nav-slot {
		/* min-width: 80px; */
		width: fit-content;



	}


	// 顶部右侧导航按钮样式
	.warp {
		display: flex;
		align-items: flex-start;
		justify-content: flex-end;
		height: 100%;

		.rect {
			margin: 30px 12px 0 0;
			min-width: 140px;
			min-height: 30px;
			background-color: #fff;
			border-radius: 12px;
		}
	}

	.MainBox {
		// padding: 0 15px;
		margin-top: 50px;
		height: 100vh;

		.TitleText {
			font-size: 24px;
			color: #333;
		}

		// 将吸顶栏的层级往下降，防止下拉框被盖住
		.u-sticky {
			z-index: 1 !important;

			// 吸顶
			.StickyBox {
				background-color: #fff;
				padding: 0 15px;

				.StickyText {
					display: flex;
					align-items: center;
					// background-color: #f6f6f6;
					height: 20px;
					line-height: 20px;

					.Round {
						width: 10px;
						height: 10px;
						border-radius: 50%;
						background-color: #49e606;
					}

					.RoundRed {
						width: 10px;
						height: 10px;
						border-radius: 50%;
						background-color: #ff0000;
					}


					.Text {
						font-size: 12px;
						margin-left: 6px;
						display: flex;
						align-items: center;

						.TextBox {
							width: fit-content;
							margin-left: 4px;
						}

						.NotText {
							width: fit-content;
							margin-left: 4px;
						}
					}
				}

				.refreshBox {
					position: absolute;
					right: 15px;
					top: 50%;
					font-size: 14px;
					color: #00aa00;
					transform: translateY(-50%);
				}
			}
		}

		// 操作界面
		.BlueToothBox {
			border: 1px solid #ccc;
			margin-top: 5px;
			margin-bottom: 5px;
			height: 35vh;
			overflow: auto;



			.FormDataBox {

				// 插口
				.uni-forms-item {

					.uni-forms-item__label {
						align-items: flex-end !important;
						background-color: pink !important;
					}

					.uni-select {
						border: none !important;

						&::after {
							position: absolute;
							box-sizing: border-box;
							content: ' ';
							pointer-events: none;
							right: 16px;
							bottom: 0;
							left: 16px;
							border-bottom: 1px solid #cbcdcf;
							-webkit-transform: scaleY(0.5);
							transform: scaleY(0.5);
						}

						// &:last-child::after {
						// 	border-bottom: none !important;
						// }
					}

				}
			}
		}

		// 标题
		.TitleBox {
			margin-top: 10px;

			.LeftTitle {
				font-size: 14px;
				font-weight: 600;
				margin-left: 8px;
			}
		}
	}

	.row {
		display: flex;
		flex-direction: row;
		align-content: flex-start;
		align-items: flex-start;
		margin: 15px 10px;
		padding: 5px;

		.button {
			width: 100px;
			font-size: 11px;
			background-color: #003366;
			color: white;
		}
	}

	.border {
		border: solid 1px gray;
	}

	.list {
		padding-left: 3vw;
		padding-right: 3vw;
		padding-top: 3vw;

		.list-item {
			background-color: #f8f8f8;
			border: solid 1px darkgray;
			box-shadow: 1px 1px 3px;
			margin-bottom: 3vw;

			.text {
				height: 30px;
				line-height: 30px;
				margin-left: 5px;
			}

			.row {
				margin: 3px 10px !important;
				padding: 0 !important;
			}
		}
	}

	.log {
		width: 87vw;
		font-size: 13px;
		color: #003366;

		.log-bottom {
			height: 10vw;
		}
	}
</style>